package org.example.JMS1.consumer;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

@Slf4j
public class QueueConsumer {
    public static final String USER_NAME = ActiveMQConnection.DEFAULT_USER;
    public static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;

    public static final String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;

    @SneakyThrows
    public static void runQueueConsumer() {

        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(USER_NAME, PASSWORD, BROKER_URL);
        Connection connection = connectionFactory.createConnection();
        connection.start();
        final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        // 指定消费队列（解耦）
        MessageConsumer consumer = session.createConsumer(session.createQueue("activeMq-queue-01"));
        // 消费者实现监听接口消费消息
        consumer.setMessageListener(message -> {
            TextMessage textMessage = (TextMessage) message;
            try {
                log.info("消息队列{}中获取textMessae：{}", "activeMq-queue-01", textMessage.getText());
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
            try {
                session.commit();
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
        });

        Thread.sleep(100 * 100);
        session.close();
        connection.close();
    }
}
